<?php  
	session_start();
	date_default_timezone_set('Asia/Shanghai');//设置时区

	//验证登录条件
	$error = "";
	$code=mb_convert_encoding($_SESSION['str'],'UTF-8','GBK');
	if (isset($_POST['cap'])&&empty($_POST['cap'])) {
		$error = "请填写验证码！";
		$num = "101";
	}elseif ($code!=$_POST['cap']) {
		$error = "验证码输入有误！";
		$num = "102";
	}elseif (isset($_POST['user'])&&empty($_POST['user'])) {
		$error = "请填写用户名！";
		$num = "103";
	}elseif (isset($_POST['pass'])&&empty($_POST['pass'])) {
		$error = "请填写密码！";
		$num = "104";
	}

	if ($error) {
		$_SESSION['error'] = $error;
		$_SESSION['num'] = $num;
		header('location:login.php');
		exit;
	}
	
	$user = addslashes($_POST['user']);
	$pass = addslashes($_POST['pass']);

	$link = mysqli_connect('localhost','root','','blog');
	mysqli_set_charset($link,'utf8');
	$sql = "SELECT * FROM `user` WHERE `user`='{$user}';";
	$r=mysqli_query($link,$sql);
	// print_r($r);
	$res=mysqli_fetch_assoc($r);
	// print_r($res);

	if (empty($res)) {
		$error = "用户名不存在，请注册！";
		$num = "105";
	}elseif($pass!=$res['password']) {
		$error = "密码输入有误！";
		$num = "106";
	}

	if ($error) {
		$_SESSION['error'] = $error;
		$_SESSION['num'] = $num;
		header('location:login.php');
		exit;
	}

	$_SESSION['user_id']=$res['id'];
	$_SESSION['user_user']=$res['user'];

	//设置自动登录的
	if (isset($_POST['login_auto'])&&$_POST['login_auto']==1) {
		$key = base_convert(sha1(uniqid(mt_rand(),true)), 16, 36);//设置密码标记是否选择免登录
		//设置过期的时间
		$start=time();
		$start_date=date('Y-m-d H-i-s',$start);
		$end=$start+10*24*3600;
		$end_date=date('Y-m-d H-i-s',$end+8*3600);
		setcookie('webkey',$key,$end);

		$link = mysqli_connect('localhost','root','','blog');
		mysqli_set_charset($link,'utf8');
		//插入用户的密码标记之前先删除同一用户之前的记录，避免冗余数据
		$sql="DELETE FROM login_auto WHERE user_id={$res['id']}";
		mysqli_query($link,$sql);
		//插入数据库，用户的数据

		$sql="INSERT INTO login_auto (web_key,start_date,end_date,user_id) VALUES('{$key}','{$start_date}','{$end_date}',{$res['id']})";
		// echo $sql;
		// echo 
		mysqli_query($link,$sql);

	}
	header("location:user.php");
	exit;


// if (isset($_POST['cap'])&&isset($_POST['user'])&&isset($_POST['pass'])) {
// 	$cap=$_POST['cap'];
// 	// $code=file_get_contents("file/code.txt");
// 	$code=$_SESSION['str'];
// 	$code=mb_convert_encoding($code,'UTF-8','GBK');
// 	// $code=strtolower($code);
// 	if ($code==$cap&&$_POST['user']=='LUOyajiang666'&&$_POST['pass']="123456") {
// 		echo "验证通过";
// 		header("location:../blog_admin/resumelist.php");
// 	}else{
// 		echo "请重新填写！";
// 		header("location:register.html");
// 	}

	// if ($code!=$cap) {
		
	// }
// }
	
?>